package wang.aweb.childcar.controller.agentApi;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import wang.aweb.childcar.common.ApiRestResponse;
import wang.aweb.childcar.common.Constant;
import wang.aweb.childcar.model.pojo.Member;
import wang.aweb.childcar.model.req.AgentLoginReq;
import wang.aweb.childcar.service.AgentService;
import wang.aweb.childcar.util.Md5Utils;
import wang.aweb.childcar.util.WechatReqUtils;

import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/agentApi/login/")
public class AgentLoginController {
    @Autowired
    private AgentService agentService;
    @Value("${agentapp.appid}")
    private String appid;
    @Value("${agentapp.secret}")
    private String appsecret;
    @PostMapping("dologin")
    @ApiOperation("代理商登录")
    public ApiRestResponse doLogin(@Valid @RequestBody AgentLoginReq agentLoginReq) throws UnsupportedEncodingException {

        JSONObject res=WechatReqUtils.getOpenIdByCode(agentLoginReq.getCode(),appid,appsecret);
        System.out.println(res);
        String openid=res.get("openid").toString();
        String username=agentLoginReq.getUsername();
        String password=agentLoginReq.getPassword();
        String md5Password= null;
        try {
            md5Password = Md5Utils.getMD5Str(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        Integer userId=agentService.doLogin(openid,username,md5Password);
        Algorithm algorithm=Algorithm.HMAC256(Constant.JWT_KEY);
        String token= JWT.create()
                .withClaim(Constant.USER_ID,userId)
                .withClaim(Constant.USER_ROLE,2)
                .withExpiresAt(new Date(System.currentTimeMillis()+Constant.EXPIRE_TIME))
                .sign(algorithm);
        Map<String,String> tokenMap=new HashMap<>();
        //        session.setAttribute(Constant.MALL_USER,user);
        tokenMap.put("token",token);
        return ApiRestResponse.success(tokenMap);
    }
}
